package com.mai4j.maiadmin.setup.db;

import com.mai4j.maiadmin.setup.Env;
import com.zaxxer.hikari.HikariDataSource;
import lombok.extern.slf4j.Slf4j;
import org.jooq.DSLContext;
import org.jooq.DropDatabaseFinalStep;
import org.jooq.SQLDialect;
import org.jooq.impl.DSL;
import picocli.CommandLine;

import java.sql.Connection;
import java.util.concurrent.Callable;

/**
 * Created by 席有芳 on 2021/11/24.
 *
 * @author 席有芳
 */
@CommandLine.Command(name = "drop", description = "删除数据库")
@Slf4j
public class Drop implements Callable<Integer> {

    @Override
    public Integer call() throws Exception {
        Env.Db db = Env.db();
        DSLContext context = DSL.using(SQLDialect.valueOf(db.getDialect()));
        try (HikariDataSource ds = new HikariDataSource();
             DropDatabaseFinalStep dropDatabase = context.dropDatabaseIfExists(db.getDatabase())) {
            ds.setJdbcUrl(db.getUrl());
            ds.setUsername(db.getUsername());
            ds.setPassword(db.getPassword());
            Connection con = ds.getConnection();
            String sql = dropDatabase.getSQL();
            log.info("SQL: " + sql);
            con.prepareStatement(sql).execute();
        }
        return 0;
    }
}
